package com.bite.forum.services.impl;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.dao.ArticleReplyMapper;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.ArticleReply;
import com.bite.forum.services.IArticleReplyService;
import com.bite.forum.services.IArticleService;
import com.bite.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {
    // 注入ArticleReplyMapper
    @Resource
    private ArticleReplyMapper articleReplyMapper;

    // 注入IArticleService
    @Resource
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        // 判断参数是否为空
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null || StringUtil.isEmpty(articleReply.getContent())) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 设置回复id和回复用户id为null
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        // 设置点赞数为0
        articleReply.setLikeCount(0);
        // 设置状态为1
        articleReply.setState((byte) 0);
        // 设置删除状态为0
        articleReply.setDeleteState((byte) 0);
        // 获取当前时间
        Date date = new Date();
        // 设置创建时间和更新时间为当前时间
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        // 插入数据
        int row = articleReplyMapper.insertSelective(articleReply);
        // 判断插入是否成功
        if(row != 1){
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        // 增加文章的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        // 记录成功日志
        log.info("回复成功，article id = " + articleReply.getArticleId() + ", user id = " +
                articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // 判断参数是否为空
        if (articleId == null || articleId <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);

        // 判断查询结果是否为空
        return result;
    }
}
